package jalus.blog;

import jalus.Action;
import jalus.service.ConfigureService;
import jalus.service.PicasaService;
import jalus.service.PostService;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.math.NumberUtils;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class PicasaServlet extends Action {
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		
		PicasaService picasaService = PicasaService.getInstance();
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("focustab", "album");
		root.put("config", ConfigureService.getInstance());
		root.put("spinpostlist", PostService.getInstance().getSpinPostList());
		root.put("userService", userService);
		root.put("uri", req.getRequestURI());
		
		String albumName = req.getParameter("albumName");
		String templatePath;
		if(albumName == null){
			albumList(picasaService, root);
			templatePath = "albumList.html";
		}else{
			int photoid = NumberUtils.toInt(req.getParameter("photoid"), -1);
			if(photoid >= 0){
				photo(picasaService, root, albumName, photoid);
				templatePath = "photo.html";
			}else{
				photoList(picasaService, root, albumName);
				templatePath = "photoList.html";
			}
		}
		
        processTemplate(root, templatePath, resp);
	}
	
	/* 相册列表 */
	private void albumList(PicasaService picasaService, Map<String, Object> root) throws IOException{
		List<jalus.pojo.AlbumEntry> albumList = picasaService.getAblumList();
		root.put("albumlist", albumList);
	}
	
	/* 相册内照片列表 */
	private void photoList(PicasaService picasaService, Map<String, Object> root, String albumName)
			throws IOException{
		jalus.pojo.AlbumFeed albumFeed = picasaService.getPhotoListByAlbum(albumName);
		List<jalus.pojo.PhotoEntry> photoList = albumFeed.getPhotoEntries();
		root.put("photolist", photoList);
		root.put("albumhname", albumFeed.getName());
		root.put("albumname", albumFeed.getTitle());
	}
	/* 某张照片 */
	private void photo(PicasaService picasaService, Map<String, Object> root, String albumName, int photoId)
			throws IOException{
		jalus.pojo.AlbumFeed albumFeed = picasaService.getPhotoListByAlbum(albumName);
		List<jalus.pojo.PhotoEntry> photoList = albumFeed.getPhotoEntries();
		jalus.pojo.PhotoEntry photo = photoList.get(photoId);
		root.put("photolist", photoList);
		root.put("photo", photo);
		root.put("albumname", albumFeed.getTitle());
		root.put("albumhname", albumFeed.getName());
	}
}
